package cn.thens.kdroid.core.log

import android.util.Log
import java.io.OutputStream
import java.io.PrintStream
import java.text.SimpleDateFormat
import java.util.*

object Loggers {
    private var logcatTagPrefix = 0

    fun logcat(): ILogger {
        return ILogger { priority, tag, message ->
            logcatTagPrefix = (logcatTagPrefix + 1) % 10
            Log.println(priority, "$logcatTagPrefix.$tag", message)
        }
    }

    fun from(printer: IPrinter): ILogger {
        return object : ILogger {
            private val dateFormat = SimpleDateFormat("MM.dd HH:mm:ss.SSS", Locale.UK)
            private val date = Date()
            override fun log(priority: Int, tag: String, message: String) {
                date.time = System.currentTimeMillis()
                val time = dateFormat.format(date)
                val level = when (priority) {
                    ILogger.VERBOSE -> "V"
                    ILogger.DEBUG -> "D"
                    ILogger.INFO -> "I"
                    ILogger.WARN -> "W"
                    ILogger.ERROR -> "E"
                    else -> "A"
                }
                printer.print("[$time] $level/$tag: $message")
            }
        }
    }

    fun out(output: OutputStream = System.out): ILogger {
        return from(IPrinter { message -> PrintStream(output).println(message) })
    }
}